<template>
	<view class="connect-page">
		<view class="connect-top">
			<view class="connect-image">
				<image src="@/static/connect.jpg" mode="" class="connect-image-size"></image>
			</view>
			<view class="connect-tip">
				请将保持手机蓝牙开启并将手机尽量靠近设备
			</view>
			<view class="connect-status">
				<image src="@/static/icons/bindSuccess.svg" mode="" class="connect-status-icon"></image>
				连接设备成功
			</view>
			<view class="connect-status" v-if="success">
				<image src="@/static/icons/bindSuccess.svg" mode="" class="connect-status-icon"></image>
				设备账号绑定成功
			</view>
		</view>
		<view class="connect-bottom">
			<view class="connect-bottom-btn" @click="next">
				下一步
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'

	import {
		blufi
	} from '../../utils/blufi.js';
	import {
		BluetoothStore
	} from '@/store/Bluetooth.js'
	const blueStore = BluetoothStore()
	const form = ref({
		name: '空调机',
		uid: "kt201506140100001"
	});
	const success = ref(false)

	const devData = ref({})
	const wifiInfo = ref({
		ssid: '',
		password: ''
	})
	onLoad(async (option) => {
		wifiInfo.value.ssid = decodeURIComponent(option.ssid);
		wifiInfo.value.password = decodeURIComponent(option.pass);
		devData.value = blueStore.getDeviceInfo();
		form.value.name = devData.value.localName;
		form.value.uid = devData.value.deviceId;
		initBluetooth()
	})

	const initBluetooth = async () => {
		wx.openBluetoothAdapter({
			success: () => {
				// wx.createBLEConnection({
				// 	deviceId: form.value.uid,
				// 	success: (res) => {
				try {
					blufi.sendSsidAndPassword(wifiInfo.value.ssid, wifiInfo.value
						.password);

					success.value = true;
				} catch (e) {
					uni.showToast({
						title: '设备绑定失败',
						icon: 'none'
					})
				}
			},
			fail: (e) => {
				console.log(e, '初始化失败')
				uni.showToast({
					title: '蓝牙模块初始化失败',
					icon: 'none'
				})
			}
		})
	}


	// 下一步 添加设备
	const next = () => {
		if (!success.value) {
			uni.showToast({
				title: '请等待设备绑定成功',
				icon: 'none'
			})
			return;
		}
		wx.closeBluetoothAdapter({
			success(res) {
				console.log('关闭蓝牙模块', res)
			}
		})
		const encodedUid = encodeURIComponent(form.value.uid);
		uni.navigateTo({
			url: `/Device/AddManually/AddManually?uid=${encodedUid}&&isBluetooth=true`
		})
	}
</script>

<style lang="scss" scoped>
	@import "./connectDevice.scss";
</style>